'use strict';

const Service = require('egg').Service;

const PRODUCT_TYPE = {
	private:1, // 私有
	public:2, // 共有
};

const PRODUCT_TAG = {
	hot: 1,// 热门产品
}

const PRODUCT_STATUS = {
	online: 1, // 上架
	offline: 2, // 下架
}

class ProductService extends Service {

	get tbname(){
		return 'yz_product';
	}

	async hotList(){
		const { app } = this;
		// let test = {"width":100, "height":300, "uri":'https://i.imgur.com/UYiroysl.jpg'};
		// const result = await app.mysql.insert('yz_product',{
		// 	depid:1,
		// 	uid:1,
		// 	title:'测试产品3',
		// 	status:1,
		// 	type:3,
		// 	content:'热门产品2',
		// 	image: JSON.stringify(test),
		// 	ctime:'2019-01-02 18:42:45',
		// });

		const list = await app.mysql.select(this.tbname, {
			where: { status: PRODUCT_STATUS.online, tag: PRODUCT_TAG.hot },
			orders: [['id','desc']],
			limit:6,
			offset:0,
		});
		list.forEach(item => item.image = JSON.parse(item.image));
		return list;
	}

	async list(param){
		const { app } = this;
		let where = ` status = ${PRODUCT_STATUS.online} AND type = ${param.type}`;
		if(param.key){
			where = where.concat(` AND content like '%${param.key}%'`);
		}
		let offset = (param.pageNum - 1) * param.pageSize;
		const list = await app.mysql.query(`select * from ${this.tbname} where ${where} order by id desc limit ${offset},${param.pageSize}`);

		list.forEach(item => item.image = JSON.parse(item.image));
		return list;
	}
}

module.exports = ProductService;